package com.member.web.controller.user;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.member.common.utils.DateUtils;
import com.member.common.utils.ExcelHandle;
import com.member.entity.CarActivity;
import com.member.entity.ChuTuan;
import com.member.entity.EatActivity;
import com.member.entity.GoodsActivity;
import com.member.entity.Shopping;
import com.member.entity.StayActivity;
import com.member.entity.User;
import com.member.entity.YeWu;
import com.member.entity.vo.ChuTuanVo;
import com.member.entity.vo.UserShoppingVo;
import com.member.service.UserService;
import com.member.web.controller.BaseController;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@Autowired
	UserService userService;
	
	//跳转添加会员页面
	@RequestMapping("/tiao")
	public String tiao(){
		return "user/insert_user";
	}
	
	//添加会员
	@RequestMapping("/insertUser")
	public String insertUser(String name, String idNum,String businessManager,String address, String phone, String cardNum, String createCardTime,
			String integration, String level,String organizerName, Model model) {
		if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(businessManager)&& StringUtils.isNotEmpty(address) && StringUtils.isNotEmpty(phone)) {
			userService.insertUser(name, idNum,businessManager,address, phone, cardNum, createCardTime, integration, level,organizerName);
			return "redirect:userList";
		} else {
			model.addAttribute("ERROR", "参数有误");
			return "user/insert_user";
		}
	}

	// 查找所有会员
	@RequestMapping("/userList")
	public String userList(Model model, Integer pageNum, Integer pageSize) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 50;
		PageInfo<User> userList = userService.selectAllUser(pageNum, pageSize);
		model.addAttribute("page", userList);
		return "user/user_list";
	}

	//按建卡时间排序
	@RequestMapping("/sort")
	public String sort(Model model, String key,String sortNum, Integer pageNum, Integer pageSize){
			if (pageNum == null)
				pageNum = 1;
			if (pageSize == null)
				pageSize = 50;
			PageInfo<User> user = userService.selectUserByKey(key,sortNum, pageNum, pageSize);
			model.addAttribute("page", user);
			
			List<String> params = new ArrayList<String>();
			 if(sortNum!=null  ){
				 String param1 = "sortNum="+sortNum+"&";
				 params.add(param1);
			 }
			 if(key!=null && key.length()!=0  ){
				 String param1 = "key="+key+"&";
				 params.add(param1);
			 }

			model.addAttribute("params", params);
			
			return "user/user_list";
//		}
		
	}
	
	//删除会员
	@RequestMapping("/deleteUser")
	public String deleteUser(String id,Model model){
		userService.deleteUser(id);
		return "redirect:userList";
	}
	
	//模态框回显
	@ResponseBody
	@RequestMapping("/selectUser")
	public User selectUser(String id){
		User user = userService.selectUser(id);
		return user;
	}
	
	//修改会员信息
	@RequestMapping("/updateUser")
	public String updateUser(String id, String idNum,String businessManager,String name, String address, String phone, String cardNum, String createCardTime,
			String integration, String level,String organizerName){
		userService.updateUser(id,name, idNum,businessManager,address, phone, cardNum, createCardTime, integration, level,organizerName);
		return "redirect:userList";
	}
	
	//检查会员名是否重复
	@ResponseBody
	@RequestMapping("/checkUser")
	public String checkUser(String name){
		if (userService.checkUser(name)!=null && !userService.checkUser(name).isEmpty()) {
			return "1";
		} else {
			return "0";
		}
	}
	@RequestMapping("/loginView")
	public String view() {
		return "login";
		
	}
	@RequestMapping("/findshoplist")
	public String findshoplist(String name,String phone,Model model,Integer pageNum, Integer pageSize) {
			if (pageNum == null)
				pageNum = 1;
			if (pageSize == null)
				pageSize = 10;
		PageInfo<UserShoppingVo> list=userService.findshoplist(name,phone,pageNum, pageSize);
		model.addAttribute("page", list);
		return "user/shoplist";
		
	}
	@ResponseBody
	@RequestMapping("/findShoppingTaoChan")
	public List<GoodsActivity> findShoppingTaoChan(String id) {
		List<GoodsActivity>  list=userService.findShoppingTaoChanById(id);
		return list;
		
	}
	@RequestMapping("/tuihuo")
	public String tuihuo(String id,String name,String phone,Model model) {
		userService.updateTuihuo(id,name,phone);
		
		PageInfo<UserShoppingVo> list=userService.findshoplist(name,phone,1, 10);
		model.addAttribute("page", list);
		return "user/shoplist";
		
	}
	@RequestMapping("/export")
	public void findAllTransferRecordByType(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		ExcelHandle handle = new ExcelHandle();
		String tempFilePath = request.getRealPath("/resources/moban/hymb.xlsx");
		

		List<User> userList=userService.findAllUser();
		List<String> userCell = new ArrayList<String>();
		userCell.add("cardNum");
		userCell.add("name");
		userCell.add("phone");
		userCell.add("level");
		userCell.add("integration");
		userCell.add("integration1");
		userCell.add("createTime");
		userCell.add("address");
		userCell.add("idNum");
		userCell.add("default1");
		userCell.add("default2");
		userCell.add("default3");
		userCell.add("default4");
		userCell.add("default5");
		userCell.add("default6");
		userCell.add("default7");
		userCell.add("default8");
		userCell.add("default9");
		userCell.add("default10");
		userCell.add("default11");
		userCell.add("default12");
		userCell.add("default13");
		userCell.add("default14");
		userCell.add("default15");
		userCell.add("default16");
		userCell.add("default17");
		userCell.add("default18");
		userCell.add("default19");
		List<Map<String, Object>> userDataList = new ArrayList<Map<String, Object>>();
		for(User user: userList){
			
			Map<String, Object> userMap = new HashMap<String, Object>();
			if(null!=user.getCardNum()&&!("").equals(user.getCardNum().trim())){
				userMap.put("cardNum",user.getCardNum());
			}else{
				userMap.put("cardNum","0");
			}
			
			userMap.put("name",user.getName());
			userMap.put("phone",user.getPhone());
			userMap.put("level",user.getLevel());
			userMap.put("integration",user.getIntegration());
			userMap.put("integration1",user.getIntegration());
			userMap.put("createTime",DateUtils.formatDate(user.getCreateTime(),"yyyy-MM-dd"));
			userMap.put("address",user.getAddress());
			if(null!=user.getIdNum()&&!("").equals(user.getIdNum().trim())){
				userMap.put("idNum",user.getIdNum());
			}else{
				userMap.put("idNum","0");
			}
			userMap.put("default1",0);
			userMap.put("default2",0);
			userMap.put("default3",0);
			userMap.put("default4",0);
			userMap.put("default5",0);
			userMap.put("default6",0);
			userMap.put("default7",0);
			userMap.put("default8",0);
			userMap.put("default9",0);
			userMap.put("default10",0);
			userMap.put("default11",0);
			userMap.put("default12",0);
			userMap.put("default13",0);
			userMap.put("default14",0);
			userMap.put("default15",0);
			userMap.put("default16",0);
			userMap.put("default17",0);
			userMap.put("default18",0);
			userMap.put("default19",0);
			userDataList.add(userMap);
		}
		handle.writeListData(tempFilePath, userCell, userDataList,0);
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		// 写到输出流并关闭资源
		handle.writeAndClose(tempFilePath, os);
		byte[] content = os.toByteArray();
		os.flush();
		os.close();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面、
		String fileName ="会员信息表";
		
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
					
		String agent = request.getHeader("USER-AGENT").toLowerCase();
		String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		if (agent.contains("firefox")) {
			System.out.println("火狐浏览器");
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "ISO8859-1"));
		} else {
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xlsx");
		}

		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			// Simple read/write loop.
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
			
		}

		handle.readClose(tempFilePath);
		

	}
}
